<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/5/13 16:52
 */

namespace App\Logic\Order;


use App\Enums\HttpCode;
use App\Logic\CommLogic;
use App\Models\Goods\GoodsSpec;
use App\Models\Order\Refund;
use Illuminate\Database\Eloquent\Builder;
use Arr;

class RefundLogic extends CommLogic
{

    /**
     * @param array $where
     * @param array $pageData
     * @param array $sortData
     * @return \Illuminate\Http\JsonResponse
     */
    public function index($where = [], $pageData = ['pageSize' => 20, 'pageNow' => 1], $sortData = [])
    {
        $query = Refund::query()
            ->with('user')
            ->when(isset($where['uid']), function(Builder $query) use ($where){
                $query->where('uid', $where['uid']);
            })
            ->when(isset($where['status']), function (Builder $query) use ($where) {
                if ($where['status'] == 2) {
                    $query->where('status', Refund::WAIT_PAID_ORDER);
                } elseif ($where['status'] == 3) {
                    $query->whereIn('status', [Refund::SUCCESS_PAID_ORDER, Refund::WAIT_SHIPPED_ORDER]);
                }
            })
            ->when(!empty($where['name']), function (Builder $query) use ($where) {
                $query->where('name', 'like', '%' . $where['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('id', 'desc');
        }

        $data = $query->paginate($pageData['pageSize'], ['*'], 'page', $pageData['pageNow'])
            ->toArray();
        return $data;
    }

    /**
     * @param $params
     * @param $orderId
     * @return \App\Models\Model|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function show($params, $orderId)
    {
        $order = Refund::query()->with('orderGoods')->where('order_id', $orderId)->first();
        abort_if(empty($order), HttpCode::FORBIDDEN, '订单不存在！');
        $data = $order->toArray();
        $ids = explode(',', implode(',', array_column($data["order_goods"], 'sku')));
        $goodsSpec = GoodsSpec::query()->with('SpecValue')->whereIn('id', array_unique($ids))->get()->toArray();
        $spec_value = array_column($goodsSpec, 'spec_value', 'id');
        $data['gift_growth'] = $data['gift_point'] = $data['deductt_point'] = $data['coupon_discount'] = 0;
        foreach($data['order_goods'] as &$item){
            // $item['goods_thumb'] = Arr::first(array_column(json_decode($item['goods_thumb'], true), 'url'));
            $sku_name = '';
            if (!empty($item["sku"])) {
                foreach(explode(",", $item["sku"]) as $id){
                    if (isset($spec_value[$id])) {
                        $sku_name .= $spec_value[$id]['spec_value'] . ';';
                    }
                }
            }

            $data['gift_growth'] += $item['gift_growth'];
            $data['gift_point'] += $item['gift_point'];
            $data['deductt_point'] += $item['deductt_point'];
            $data['coupon_discount'] += $item['coupon_discount'];
            $item['sku_name'] = rtrim($sku_name, ';') ?? '-';
        }
        return $data;
    }

    public function store($params)
    {
        $lockName = 'refund_update_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
    }

    /**
     * @author ChenGuangHui
     * @dateTime 2022-06-14
     * @param [type] $params
     */
    public function refund($params)
    {
        # code...
    }

    /**
     * @param $params
     * @param $orderId
     * @return bool|int
     */
    public function update($params, $orderId)
    {
        $lockName = 'refund_update_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');

        $data = Refund::query()->where('order_id', $orderId)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '订单不存在！');
        return Refund::query()->where('order_id', $orderId)->update($params);
    }

    /**
     * @param $orderId
     * @return bool|mixed|null
     */
    public function destroy($orderId)
    {        
        $lockName = 'refund_update_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');

        $data = Refund::query()->where('order_id', $orderId)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '订单不存在！');
        return Refund::query()->where('order_id', $orderId)->delete();
    }
}
